import {PageContainer} from '@ant-design/pro-components';
import {Button, Card, Divider, message} from 'antd';
import {Form} from 'antd';
import moment from 'moment';
import {Descriptions} from 'antd';
import React, {useEffect, useState} from 'react';
import {getApiByIdUsingGET, invokeInterfaceInfoUsingPOST} from "@/services/api/apiController";
import {useParams} from "@@/exports";
import TextArea from "antd/es/input/TextArea";
import {FormInstance} from "antd/es/form";


const Index: React.FC = () => {
  const [loading, setLoading] = useState(false);
  const [invokeLoading, setInvokeLoading] = useState(false);
  const [invokeRes, setInvokeRes] = useState<any>();
  const [data, setData] = useState<API.Api>();
  const params = useParams();
  const formRef = React.useRef<FormInstance>(null);


  const formatterTime = (val: any) => {
    return val ? moment(val).format('YYYY-MM-DD HH:mm:ss') : ''
  }

  const onContentChange = () => {
    if (data?.requestParams) {
      formRef.current?.setFieldsValue({userRequestParam: data.requestParams});
    }
    return '';
  };

  const loadData = async () => {
    if (!params.id) {
      message.error('接口不存在')
      return;
    }
    setLoading(true);
    try {
      const res = await getApiByIdUsingGET({
        id: Number(params.id)
      });
      setData(res.data);
    } catch (e: any) {
      message.error("加载失败. " + e.message)
    }
    setLoading(false);
  }

  useEffect(() => {
    loadData();
  }, []);

  const onFinish = async (values: any) => {
    if (!params.id) {
      message.error('接口不存在')
      return;
    }
    setInvokeLoading(true);

    try {
      const res = await invokeInterfaceInfoUsingPOST({
        id: params.id,
        ...values
      })
      setInvokeRes(res.data)
      if (!res?.data) {
        message.error('请求失败');
      } else if (res.code === 0) {
        message.success('请求成功！');
      } else {
        message.error('请求失败：' + res.message);
      }
    } catch (e: any) {
      message.error("请求失败. " + e.message)
    }
    setInvokeLoading(false);
  };


  return (
    <PageContainer title='接口信息'>
      <Card size={'default'}>

        {data ? (<Descriptions title={data.name} column={1}>
          <Descriptions.Item label="接口状态">{data.status === 0 ? '关闭' : '上线'}</Descriptions.Item>
          <Descriptions.Item label="接口描述">{data.description}</Descriptions.Item>
          <Descriptions.Item label="请求地址">{data.url}</Descriptions.Item>
          <Descriptions.Item label="请求方法">{data.method}</Descriptions.Item>
          <Descriptions.Item label="请求参数示例">{data.requestParams}</Descriptions.Item>
          <Descriptions.Item label="请求头">{data.requestHeader}</Descriptions.Item>
          <Descriptions.Item label="响应头">{data.responseHeader}</Descriptions.Item>
          <Descriptions.Item label="创建时间">{formatterTime(data.createTime)}</Descriptions.Item>
          <Descriptions.Item label="更新时间">{formatterTime(data.updateTime)}</Descriptions.Item>
        </Descriptions>) : (<>接口不存在</>)}
      </Card>
      <Divider/>
      <Card title='在线测试' size={'default'}>
        <Form
          name="invoke"
          ref={formRef}
          layout='vertical'
          onFinish={onFinish}
        >
          <Form.Item
            label="请求参数"
            name="userRequestParam"
          >
            <TextArea autoSize={{minRows: 3, maxRows: 6}} wrap="off" allowClear={true} value={onContentChange()}/>
          </Form.Item>

          <Form.Item wrapperCol={{span: 16}}>
            <Button type="primary" htmlType="submit">
              调用
            </Button>
          </Form.Item>
        </Form>
      </Card>
      <Divider/>
      <Card title='返回结果' loading={invokeLoading} size={'default'}>
        <TextArea
          wrap="off"
          allowClear
          value={invokeRes}
          autoSize={{minRows: 3, maxRows: 6}}
        />
      </Card>
    </PageContainer>
  );
};

export default Index;
